package com.xuecheng.content.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class CourseCategoryServiceImpl extends ServiceImpl<CourseCategoryMapper, CourseCategory>
    implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    /**
     * 查询制定根节点的所有子节点分类
     * @param id
     * @return
     */
    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        List<CourseCategoryTreeDto> categories = courseCategoryMapper.queryTreeNodes(id);
        //然后把节点集合转换为map集合
        Map<String, CourseCategoryTreeDto> map = categories.stream()
                .filter(item -> !item.getId().equals(id))
                .collect(Collectors.toMap(CourseCategoryTreeDto::getId, category -> category,
                        (category1, category2) -> category2));
        List<CourseCategoryTreeDto> result = new ArrayList<>();
        categories.stream().filter(item -> !item.getId().equals(id)).forEach(item -> {
            if(item.getParentid().equals(id)){
                result.add(item);
            }else{
                CourseCategoryTreeDto parent = map.get(item.getParentid());
                if(parent.getChildrenTreeNodes() == null){
                    parent.setChildrenTreeNodes(new ArrayList<>());
                }
                parent.getChildrenTreeNodes().add(item);
            }
        });
        return result;
    }
}
